//
//  ClinicDetailViewController.m
//  EcmDoctor
//
//  Created by zhm on 16/2/25.
//  Copyright © 2016年 张进. All rights reserved.
//

#import "ClinicDetailViewController.h"
#import "PagedFlowView.h"
#import "NetWorkUtil.h"
#import <UIImageView+AFNetworking.h>
#import "UserAskPic.h"
#import "AppUtils.h"
#import "Treatmentsm.h"
#import "TreatmentsViewController.h"
#import "Clinic.h"
#import <AVFoundation/AVFoundation.h>
#import "DACircularProgressView.h"
#import "BigImageViewController.h"
#import "OnlineModel.h"

@interface ClinicDetailViewController ()<PagedFlowViewDataSource,AVAudioPlayerDelegate, PagedFlowViewDelegate> {
    int i;
    UIButton *btnPlayer;//播放按钮
    BOOL bl;
}

@property (nonatomic, strong) NSArray *dataAry;
@property(nonatomic,strong)AVAudioPlayer *player;
@property (nonatomic, strong) DACircularProgressView *voiceProgressView;//语音播放的圆环
@property (nonatomic, strong) NSTimer *myTimer;
@property (nonatomic, strong) UIView *blackView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *hLayout;


@end

@implementation ClinicDetailViewController

- (void)tiaozhaun {
    NSLog(@"112233!!!");
    
    //跳转到治疗方案页面
    [self performSegueWithIdentifier:@"clinicTreatmentsLine" sender:_dataAry];
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"clinicTreatmentsLine"]) {
        
        TreatmentsViewController *treatment = [segue destinationViewController];
        treatment.dataAry = sender;
        treatment.single = NO;
        treatment.i = _ifDownload;
        
    } else if ([segue.identifier isEqualToString:@"toBigimage"]) {
        BigImageViewController *big = [segue destinationViewController];
        big.imageUrl = sender;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    i = 0;
    bl = YES;
    
    _dataAry = [NSArray array];
    
    UIImage *tableIcon = [UIImage imageNamed:@"btn_back"];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeToNavRootController:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];
    
    
    self.navigationItem.titleView=[AppUtils generateNavigationItemTitleViewWithTitle:@"问题详情"];
    
    // Do any additional setup after loading the view.
    
    [self download];
    
}

- (void)download {
    if (!_blackView) {
        _blackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    }
    _blackView.backgroundColor = [UIColor blackColor];
    _blackView.alpha = 0.3;
    [self.view addSubview:_blackView];
    
    if (_ifDownload) {
        [Clinic clinicDetailWithaskId:_askId success:^(Clinic *clinic) {
            
            _sex = clinic.sex;
            _age = [clinic.age stringValue];
            _name = clinic.name;
            _headImageUrl = clinic.icon_Url;
            _detail = [NSString stringWithFormat:@"%@", clinic.content];
            _voiceUrl = clinic.voiceUrl;
            _imageUrl = clinic.picUrl;
            _askId = clinic.ask_info_id;
            
            [self creatUI];
            [_blackView removeFromSuperview];
        } failure:^(NSError *error) {
            [_blackView removeFromSuperview];
        }];
    } else {
        [self creatUI];
        [_blackView removeFromSuperview];
    }
        
}

- (void)creatUI {
    _sexLab.text = _sex;
    _ageLab.text = [NSString stringWithFormat:@"%@", _age];
    _nameLab.text = _name;
    
    if (_ifDownload == 2 || _ifDownload == 3 || _ifDownload == 4) {
        [Treatmentsm requetDoctorpcWith:_doctorId And:_askId success:^(NSArray *treatmentsAry) {
            
            if (treatmentsAry.count == 0) {
                self.navigationItem.rightBarButtonItem = [AppUtils generateNavigationBarButtonWithTitle:@"治疗方案" withTarget:self action:@selector(tiaozhaun)];
            } else {
                self.navigationItem.rightBarButtonItem = [AppUtils generateNavigationBarButtonWithTitle:[NSString stringWithFormat:@"治疗方案(%lu)", (unsigned long)treatmentsAry.count] withTarget:self action:@selector(tiaozhaun)];
            }
            _dataAry = treatmentsAry;
        } failure:^(NSError *error) {
            
        }];
    }
    
    if (_ifDownload == 3 || _ifDownload == 2) {//在已完成/未完成任务跳转时
        _hLayout.constant = 64;
    }
    
    [_headImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", [NetWorkUtil getImagesBaseUrl], _headImageUrl]] placeholderImage:[UIImage imageNamed:@"icon"]];
    _headImage.clipsToBounds = YES;
    _headImage.layer.cornerRadius = _headImage.bounds.size.width/2;
    
    _promptMessage.frame = CGRectMake(70, 10, kScreenWidth-80, 40);
    _promptMessage.text = _infoStr;
    _promptMessage.numberOfLines = 0;
    [_promptMessage sizeToFit];
    
    //"病情描述"标题
    UILabel *_bqDescTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 100, 20)];
    
    _bqDescTitle.text = @"病情描述:";
    [_detailScrollView addSubview:_bqDescTitle];
    
    CGRect rect = self.view.frame;
    double appWidth = [UIScreen mainScreen].applicationFrame.size.width;
    CGRect bqRect = _bqDescTitle.frame;
    double bqWidth =appWidth-bqRect.origin.x*2;
    
    //病情描述布局
    UILabel *_labDetail = [[UILabel alloc] initWithFrame:CGRectMake(bqRect.origin.x, bqRect.origin.y+bqRect.size.height+15, bqWidth, 21)];
    _labDetail.font = [UIFont systemFontOfSize:14];
    _labDetail.numberOfLines = 10;
    _labDetail.text = _detail;
    [_detailScrollView addSubview:_labDetail];
    [_labDetail sizeToFit];
    
    //播放音频按钮
    btnPlayer = [[UIButton alloc]initWithFrame:CGRectMake(rect.size.width/2-30, CGRectGetMaxY(_labDetail.frame)+15, 70, 70)];
    [btnPlayer addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    btnPlayer.tag = 10000;
    btnPlayer.layer.cornerRadius = 35;
    btnPlayer.clipsToBounds = YES;
    
    [btnPlayer setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
    
    //初始化语音圈
    self.voiceProgressView = [[DACircularProgressView alloc] initWithFrame:CGRectMake(rect.size.width/2-30, CGRectGetMaxY(_labDetail.frame)+15, 70, 70)];
    //声音播放进度条
    self.voiceProgressView.progressTintColor = [UIColor blackColor];
    self.voiceProgressView.trackTintColor = [UIColor lightGrayColor];
    self.voiceProgressView.progress = 0;
    self.voiceProgressView.borderWidth = 5;
    
    //判断是否有音频
    if (_voiceUrl != nil && ![_voiceUrl isEqualToString:@""]) {
        if (_player) {
            _player = nil;
        }
        [_detailScrollView addSubview:self.voiceProgressView];
        [_detailScrollView addSubview:btnPlayer];
        
    }
    
    
    //分割线
    UIView *splitLine = [[UIView alloc] init];
    
    if (_voiceUrl != nil && ![_voiceUrl isEqualToString:@""]) {
        splitLine.frame = CGRectMake(0, btnPlayer.frame.origin.y+btnPlayer.frame.size.height+20, appWidth, 0.5);
    } else {
        
        splitLine.frame = CGRectMake(0, _labDetail.frame.origin.y+_labDetail.frame.size.height+20, appWidth, 0.5);
    }
    
    splitLine.backgroundColor = [UIColor colorWithRed:241.0/255 green:224.0/255 blue:204.0/255 alpha:1.0];
    [_detailScrollView addSubview:splitLine];
    
    //"患处照片"文字布局
    UILabel *picTitle =[[UILabel alloc] initWithFrame:CGRectMake(bqRect.origin.x, splitLine.frame.origin.y+splitLine.frame.size.height+10, bqWidth, 21)];
    picTitle.numberOfLines = 1;
    picTitle.text = @"患处照片：";
    [picTitle setFont:[UIFont fontWithName:@"Helvetica" size:13]];
    if (_imageUrl.count != 0 && _imageUrl) {
        [_detailScrollView addSubview:picTitle];
    }
    
    //图片滚动框
    PagedFlowView *pageFlowView = [[PagedFlowView alloc] initWithFrame:CGRectMake(0, picTitle.frame.origin.y+picTitle.frame.size.height+10, appWidth+10, appWidth)];
    
    //    pageFlowView.delegate = self;
    pageFlowView.dataSource = self;
    pageFlowView.delegate = self;
    pageFlowView.minimumPageAlpha = 1;
    pageFlowView.minimumPageScale = 1;
    pageFlowView.backgroundColor = [UIColor colorWithRed:254.0/255 green:246.0/255 blue:233.0/255 alpha:1.0];
    if (_imageUrl.count != 0) {
        [_detailScrollView addSubview:pageFlowView];
    }
    if (_voiceUrl != nil && ![_voiceUrl isEqualToString:@""])
        [_detailScrollView setContentSize:CGSizeMake(0, kScreenHeight-164+btnPlayer.bounds.size.height)];
    else
        [_detailScrollView setContentSize:CGSizeMake(0, kScreenHeight-164)];
        
        
    if (_ifDownload) {
        
        UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 164, kScreenWidth, kScreenHeight-164)];
        //        scroll.backgroundColor = [UIColor redColor];
        scroll.backgroundColor = [UIColor colorWithRed:254.0/255 green:246.0/255 blue:233.0/255 alpha:1.0];
        [self.view addSubview:scroll];
        [_detailScrollView removeFromSuperview];
        [scroll addSubview:_bqDescTitle];
        [scroll addSubview:_labDetail];
        //判断是否有音频
        if (self.voiceUrl != nil && ![self.voiceUrl isEqualToString:@""]) {
            if (_player) {
                _player = nil;
            }
            [scroll addSubview:btnPlayer];
            [scroll addSubview:_voiceProgressView];
            [scroll setContentSize:CGSizeMake(0, kScreenHeight-109+btnPlayer.bounds.size.height+15)];
        } else
            [scroll setContentSize:CGSizeMake(0, kScreenHeight-109)];
        [scroll addSubview:splitLine];
        if (_imageUrl.count != 0 && _imageUrl) {
            [scroll addSubview:picTitle];
            [scroll addSubview:pageFlowView];
        }
    }
}

#pragma PagedFlowViewDataSource implement
//返回显示View的个数
- (NSInteger)numberOfPagesInFlowView:(PagedFlowView *)flowView{
    return _imageUrl.count;
}

//返回给某列使用的View
- (UIView *)flowView:(PagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    UIImageView *imageView = [[UIImageView alloc] init];
    //    imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg",index+1]];
    UserAskPic *ask = _imageUrl[index];
    [imageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://192.168.1.100:1443/EChineseMedicine/rs/FileRS/resourceImage/%@", ask.user_ask_pic]]];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    return imageView;
}

- (void)flowView:(PagedFlowView *)flowView didTapPageAtIndex:(NSInteger)index{
    UserAskPic *askPic = [_imageUrl objectAtIndex:index];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[NetWorkUtil getImagesBaseUrl],askPic.user_ask_pic];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    [self performSegueWithIdentifier:@"toBigimage" sender:url];
}

-(void)changeToNavRootController:(id)sender{
    
    if (_ifDownload) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }

}

//播放音频
- (void)buttonClicked:(UIButton *)btn {
    //本地路径
    NSString *myPath = [NSString stringWithFormat:@"%@/Documents/DataCache/%@",NSHomeDirectory(), [NSString stringWithFormat:@"https://192.168.1.100:1433/EChineseMedicine/rs/FileRS/resourceVoice/%@", self.voiceUrl]];
    bl = [[NSBundle mainBundle] pathForResource:myPath ofType:@""];
    
    //按钮的状态
    if (i == 0) {
        
        if (bl == NO) {//判断是否下载成功或有本地数据
            [self downloadVoice:myPath];
        } else {
            [self playVoice];
            [btnPlayer setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
            i = 1;
        }
        
    } else {
        [btnPlayer setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [_player pause];
        i = 0;
    }
}
//下载
- (void)downloadVoice:(NSString *)urlStr {
    
    //先下载到本地再播放
    [NetWorkUtil playerVoiceWithVoiceName:self.voiceUrl success:^(NSString *responseObject) {
        [btnPlayer setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
        i = 1;
        [self playVoice];
        
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)playVoice {
    bl = NO;//成功下载后设置为no
    
    //本地路径
    NSString *myPath = [NSString stringWithFormat:@"%@/Documents/DataCache/%@",NSHomeDirectory(), [NSString stringWithFormat:@"https://192.168.1.100:1433/EChineseMedicine/rs/FileRS/resourceVoice/%@", _voiceUrl]];
    
    if (_player) {
        _player = nil;
    }
    
    //创建播放器
    //    _player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"song1.mp3" ofType:nil]] error:nil];
    _player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:myPath] error:nil];
    [_player play];
    _player.delegate = self;
    
    //通过定时器使进度条与声音同步
    _myTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(audioPlayerChangeSlider:) userInfo:nil repeats:YES];
}

#pragma mark--AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
{
    i = 0;
    self.voiceProgressView.progress = 0;
    [btnPlayer setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
}

-(void)audioPlayerChangeSlider:(NSTimer *)time{
    //进度条赋值 进度条长度为1
    self.voiceProgressView.progress = _player.currentTime/_player.duration;
    NSLog(@"%f", self.voiceProgressView.progress);
    if (_player.currentTime == _player.duration) {
        //        i = 0;
        //        [btnPlayer setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [time invalidate];
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    //停止播放
    //停止定时器
    [_player stop];
    [_myTimer invalidate];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
        
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
        
    }
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
